package com.lkd.handler;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Topic(TopicConfig.VMS_STATUS_TOPIC)
@Slf4j
public class SupplyMsgHandler implements MsgHandler {

    @Resource
    private VMService vmService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private TaskService taskService;


    @Override
    public void process(String jsonMsg) throws IOException {
        log.info("接收到补货任务消息：{}", jsonMsg);
        //1.接收消息，转化为协议对象
        if (StringUtils.isEmpty(jsonMsg)) {
            return;
        }
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        if (supplyContract == null || StringUtils.isEmpty(supplyContract.getInnerCode()) || CollectionUtils.isEmpty(supplyContract.getSupplyData())) {
            return;
        }

        //2.封装数据，调用业务层创建补货工单
        TaskViewModel taskViewModel = new TaskViewModel();
        taskViewModel.setInnerCode(supplyContract.getInnerCode());
        taskViewModel.setCreateType(0);
        taskViewModel.setDesc("自动补货工单");
        taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);
        taskViewModel.setUserId(findMinTaskCountUser(taskViewModel));

        List<TaskDetailsViewModel> detailsViewModel = supplyContract.getSupplyData().stream().map(supplyChannel -> {
            TaskDetailsViewModel model = new TaskDetailsViewModel();
            model.setSkuName(supplyChannel.getSkuName());
            model.setSkuImage(supplyChannel.getSkuImage());
            model.setSkuId(supplyChannel.getSkuId());
            model.setExpectCapacity(supplyChannel.getCapacity());
            model.setChannelCode(supplyChannel.getChannelId());
            return model;
        }).collect(Collectors.toList());


        taskViewModel.setDetails(detailsViewModel);

        taskService.create(taskViewModel);
    }


    /**
     * 查询当前任务数量最少的人员
     *
     * @param taskViewModel
     * @return
     */
    private Integer findMinTaskCountUser(TaskViewModel taskViewModel) {
        //任务执行时间
        String format = new SimpleDateFormat("yyyyMMdd").format(new Date());
        //任务执行区域
        VmVO vmInfo = vmService.getVMInfo(taskViewModel.getInnerCode());
        String roleCode = "1002";
        if (taskViewModel.getProductType() != VMSystem.TASK_TYPE_SUPPLY) {
            roleCode = "1003";
        }

        String key = VMSystem.REGION_TASK_KEY_PREF + format + "." + vmInfo.getRegionId() + "." + roleCode;

        Integer userid = (Integer) redisTemplate.opsForZSet().range(key, 0, 1).stream().findFirst().get();

        return userid;
    }
}
